# -*- coding: utf-8 -*
'''
    Created by XiaoInk at 2021/10/10 17:45:39
    Gitee: https://gitee.com/XiaoInk
'''

from flask import request
from flask.json import jsonify
from werkzeug.security import generate_password_hash, check_password_hash

from app import app, dao
from app.macros import macros
from app.tools import gen_unique_str


@app.route('/api/auth/register', methods=['POST'])
def register():
    '''注册
    :param username 用户名
    :param password 密码
    '''
    username = request.form.get('username')
    password = request.form.get('password')

    if not (username and password):
        return jsonify(code=macros.HTTP.StatusBadRequest, msg='必传参数不能为空')

    if dao.user.find_by_username(username):
        return jsonify(code=macros.HTTP.StatusBadRequest, msg='该用户已注册')

    user = dao.user.create(username, generate_password_hash(password))
    if not user:
        return jsonify(code=macros.HTTP.StatusBadRequest, msg='注册失败')

    return jsonify(code=macros.HTTP.StatusCreated, msg='注册成功')


@app.route('/api/auth/login', methods=['POST'])
def login():
    '''登录
    :param username 用户名
    :param password 密码
    '''
    username = request.form.get('username')
    password = request.form.get('password')

    if not (username and password):
        return jsonify(code=macros.HTTP.StatusBadRequest, msg='必传参数不能为空')

    user = dao.user.find_by_username(username)
    if not user:
        return jsonify(code=macros.HTTP.StatusBadRequest, msg='用户不存在')

    if not check_password_hash(user['password'], password):
        return jsonify(code=macros.HTTP.StatusBadRequest, msg='用户名或密码错误')

    # 生成token
    token = gen_unique_str()
    # 缓存token
    dao.token.set(token, user['id'], 60*60)

    return jsonify(code=macros.HTTP.StatusOK, msg='登录成功', token=token)


@app.route('/api/auth/logout', methods=['POST'])
def logout():
    '''注销'''
    dao.token.delete(request.headers.get('Authorization'))

    return jsonify(code=macros.HTTP.StatusOK, msg='ok')


if __name__ == '__main__':
    pass
